#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
古诗全文数据库创建和更新脚本
"""

from poem_content_manager import PoemContentManager
from poem_recite import poems

def main():
    print("=== 古诗全文数据库创建和更新工具 ===")
    
    # 创建内容管理器实例
    manager = PoemContentManager()
    
    print(f"已加载 {len(manager.poem_contents)} 首诗词缓存")
    print(f"诗词列表包含 {len(poems)} 首诗词")
    
    # 显示菜单
    while True:
        print("\n请选择操作：")
        print("1. 批量更新所有诗词内容")
        print("2. 更新指定诗词内容")
        print("3. 搜索本地诗词")
        print("4. 查看已缓存诗词列表")
        print("5. 导出诗词内容到文件")
        print("6. 清空本地缓存")
        print("7. 退出")
        
        choice = input("\n请输入选项（1-7）：").strip()
        
        if choice == "1":
            batch_update_all(manager)
        elif choice == "2":
            update_specific_poem(manager)
        elif choice == "3":
            search_local_poems(manager)
        elif choice == "4":
            show_cached_poems(manager)
        elif choice == "5":
            export_poems(manager)
        elif choice == "6":
            clear_cache(manager)
        elif choice == "7":
            print("谢谢使用！")
            break
        else:
            print("无效选项，请重新选择。")

def batch_update_all(manager):
    """批量更新所有诗词内容"""
    print("\n开始批量更新诗词内容...")
    
    results = manager.batch_update_poems(poems)
    
    success_count = sum(1 for success in results.values() if success)
    total_count = len(results)
    
    print(f"\n更新完成！成功: {success_count}/{total_count}")
    
    # 显示失败的诗词
    failed_poems = [name for name, success in results.items() if not success]
    if failed_poems:
        print(f"\n未找到内容的诗词 ({len(failed_poems)} 首):")
        for poem in failed_poems:
            print(f"  - {poem}")

def update_specific_poem(manager):
    """更新指定诗词内容"""
    print("\n请输入要更新的诗词名称（支持部分匹配）：")
    keyword = input().strip()
    
    if not keyword:
        print("请输入有效的诗词名称。")
        return
    
    # 查找匹配的诗词
    matched_poems = []
    for num, name in poems:
        if keyword.lower() in name.lower():
            matched_poems.append((num, name))
    
    if not matched_poems:
        print(f"未找到包含 '{keyword}' 的诗词。")
        return
    
    if len(matched_poems) == 1:
        num, name = matched_poems[0]
        print(f"找到诗词: {name}")
        content = manager.get_poem_content(name)
        if content:
            print(f"成功更新: {name}")
            print("内容预览:")
            print("-" * 30)
            print(content[:100] + "..." if len(content) > 100 else content)
            print("-" * 30)
        else:
            print(f"未能获取 {name} 的内容。")
    else:
        print(f"找到 {len(matched_poems)} 首相关诗词:")
        for i, (num, name) in enumerate(matched_poems, 1):
            print(f"{i}. {name}")
        
        try:
            choice = int(input("请选择要更新的诗词序号: ")) - 1
            if 0 <= choice < len(matched_poems):
                num, name = matched_poems[choice]
                content = manager.get_poem_content(name)
                if content:
                    print(f"成功更新: {name}")
                    print("内容预览:")
                    print("-" * 30)
                    print(content[:100] + "..." if len(content) > 100 else content)
                    print("-" * 30)
                else:
                    print(f"未能获取 {name} 的内容。")
            else:
                print("无效的选择。")
        except ValueError:
            print("请输入有效的数字。")

def search_local_poems(manager):
    """搜索本地诗词"""
    keyword = input("\n请输入搜索关键词: ").strip()
    
    if not keyword:
        print("请输入有效的关键词。")
        return
    
    results = manager.search_local_poems(keyword)
    
    if not results:
        print(f"未找到包含 '{keyword}' 的诗词。")
        return
    
    print(f"\n找到 {len(results)} 首相关诗词:")
    for name, content in results:
        print(f"\n诗名: {name}")
        print("-" * 30)
        # 显示包含关键词的行
        lines = content.split('\n')
        for line in lines:
            if keyword in line:
                print(f">>> {line}")
        print("-" * 30)

def show_cached_poems(manager):
    """显示已缓存诗词列表"""
    cached_poems = manager.get_all_cached_poems()
    
    if not cached_poems:
        print("\n本地缓存为空。")
        return
    
    print(f"\n已缓存 {len(cached_poems)} 首诗词:")
    for i, name in enumerate(cached_poems, 1):
        print(f"{i}. {name}")

def export_poems(manager):
    """导出诗词内容到文件"""
    filename = input("\n请输入导出文件名（默认: exported_poems.txt）: ").strip()
    if not filename:
        filename = "exported_poems.txt"
    
    if manager.export_to_file(filename):
        print(f"诗词内容已导出到: {filename}")
    else:
        print("导出失败。")

def clear_cache(manager):
    """清空本地缓存"""
    confirm = input("\n确定要清空所有本地缓存吗？(y/n): ").strip().lower()
    if confirm == 'y':
        if manager.clear_cache():
            print("本地缓存已清空。")
        else:
            print("清空缓存失败。")
    else:
        print("操作已取消。")

if __name__ == "__main__":
    main()